package com.yjw.rpc;

import com.yjw.rpc.IoUtils;
import com.yjw.rpc.RpcRequest;
import sun.nio.ch.IOUtil;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author: James Yin
 * @description:
 * @date: 2/10/2020 11:01 PM
 */
public class RpcNetTransport {

    private String host;
    private int port;

    public RpcNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Object send(RpcRequest rpcRequest) {
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Object result = null;
        try {
            socket = new Socket(host, port);
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(rpcRequest);
            oos.flush();

            ois = new ObjectInputStream(socket.getInputStream());
            result = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtils.close(ois, oos, socket);
        }
        return result;
    }
}
